library(ggpubr)
library(tidyverse)
library(ggplot2)
library(dplyr)

# 1. Distribution
set.seed(1234)
wdata <- data.frame(sex = factor(rep(c('F', 'M'), each = 200)),
                    weight = c(rnorm(200, 55), rnorm(200, 58)))
head(wdata)

# 1.1. Density plot with mean lines and marginal rug
# Use custom palette
ggdensity(wdata, x = 'weight',
          add = 'mean', rug = TRUE,
          color = 'sex', fill = 'sex',
          palette = c('#00AFBB', '#E7B800'))

# 1.2 Histogram plot with mean lines and marginal rug
gghistogram(wdata, x = 'weight',
            add = 'mean', rug = TRUE,
            color = 'sex', fill = 'sex',
            pallette = c('#00AFBB', '#E7B800'))


# 2. Boxplot and Violin plot
data('ToothGrowth')
df <- ToothGrowth
head(df, 4)

# 2.1 Boxplot with jittered points
# Change outline colors by groups: dose
# Use custom color palette
# Add jitter points and change the shape by groups
p <- ggboxplot(df, x = 'dose', y = 'len',
               color = 'dose', pallette = c("#00AFBB", "#E7B800", "#FC4E07"),
               add = 'jitter', shape = 'dose')
p

# Add p-values comparing groups
# Specify the comparisions you want
my_comparisons <- list(c("0.5", "1"), c("1", "2"), c("0.5", "2"))
p + stat_compare_means(comparisons = my_comparisons) + # Add pairwise comparison p-value
    stat_compare_means(label.y = 50) # Add global p-value

# 2.2 Violin plots with box plots inside
ggviolin(df, x = 'dose', y = 'len', fill = 'dose',
         palette = c("#00AFBB", "#E7B800", "#FC4E07"),
         add = 'boxplot', add.params = list(fill = 'white')) +
    stat_compare_means(comparisons = my_comparisons, label = 'p.signif') + 
    stat_compare_means(label.y = 50)


# 3. Barplot
data('mtcars')
dfm <- mtcars
dfm$cyl <- as.factor(dfm$cyl) # Convert the cyl to a factor
dfm$name <- rownames(dfm) # Add the name column
head(dfm[, c("name", "wt", "mpg", "cyl")])

## 3.1 Ordered bar plots (asceding)
ggbarplot(dfm, x = 'name', y = 'mpg',
          fill = 'cyl',           # change fill color by cyl
          color = 'white',        # set bar border colors to white
          palette = 'jco',        # jco journal color palett (?ggpar)
          sort.val = 'desc',      # sort the value in descending order
          sort.by.groups = FALSE, # don't sort inside each group
          x.text.angle = 90)      # rotate vertically x axis texts

## sort bars inside each group (sort.by.groups = T)
ggbarplot(dfm, x = 'name', y = 'mpg',
          fill = 'cyl',          # change fill color by cyl
          color = 'white',       # set bar border color to white
          palette = 'jco',       # jco journal color palette (?ggpar)
          sort.val = 'asc',      # sort the value in ascending order
          sort.by.groups = TRUE, # sort inside each group
          x.text.angle = 90)     # rotate vertically x axis texts


# 3.2 Deviation graph
dfm$mpg_z <- (dfm$mpg - mean(dfm$mpg)) / sd(dfm$mpg)
dfm$mpg_grp <- factor(ifelse(dfm$mpg_z < 0, "low", "high"),
                      levels = c("low", "high"))
head(dfm[, c("name", "wt", "mpg", "mpg_z", "mpg_grp", "cyl")])

ggbarplot(dfm, x = "name", y = "mpg_z",
          fill = "mpg_grp",
          color = "white",
          palette = "jco",
          sort.val = "asc",
          sort.by.groups = FALSE,
          x.text.angle = 90,
          ylab = "MPG z-score",
          xlab = FALSE,
          legend.title = "MPG Group")

## rotate the plot
ggbarplot(dfm, x = "name", y = "mpg_z",
          fill = "mpg_grp",
          color = "white",
          palette = "jco",
          sort.val = "desc",
          sort.by.groups = FALSE,
          x.text.angle = 90,
          ylab = "MPG z-score",
          legend.title = "MPG Group",
          rotate = TRUE,
          ggtheme = theme_minimal())

# 4. Dot charts

# 4.1 Lollipop chart (similar to barplot)
ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",                                # color by groups
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), # custom color palette
           sorting = "ascending",                        # sort value in descending order
           add = "segments",                             # add segments from y=0 to dots
           ggtheme = theme_pubr())                       # ggplot2 theme

# Setting parameters
ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), 
           sorting = "descending",
           add = "segments",
           rotate = TRUE,
           group = "cyl",
           dot.size = 6,
           label = round(dfm$mpg),
           font.label = list(color = "white", size = 9, 
                             vjust = 0.5),
           ggtheme = theme_pubr())

# 4.2 Deviation plot
ggdotchart(dfm, x = "name", y = "mpg_z",
           color = "cyl",
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), 
           sorting = "descending",
           add = "segments",
           add.params = list(color = "lightgray", size = 2),
           group = "cyl",
           dot.size = 6,
           label = round(dfm$mpg_z, 1),
           font.label = list(color = "white", size = 9,
                             vjust = 0.5),
           ggtheme = theme_pubr()) +
    geom_line(yintercept = 0, linetype = 2, color = "lightgray")

# 4.2 Cleveland's dot plot
ggdotchart(dfm, x = "name", y = "mpg",
           color = "cyl",
           palette = c("#00AFBB", "#E7B800", "#FC4E07"), 
           sorting = "descending",
           rotate = TRUE,
           dot.size = 2,
           y.text.col = TRUE,
           ggtheme = theme_pubr()) +
    theme_cleveland()

#########
df <- mtcars
df$cyl <- as.factor(df$cyl)

# scatter plot with confidence ellipses
ggscatter(df, x = "wt", y = "mpg", color = "cyl") +
    stat_conf_ellipse(aes(color = cyl))

ggscatter(df, x = "wt", y = "mpg", color = "cyl") +
    stat_conf_ellipse(aes(color = cyl, fill = cyl), alpha = 0.1, geom = "polygon")


# add_summary() ----
#   add statistical info on figure (mean, SD, SE etc.)
p <- ggviolin(ToothGrowth, x = "dose", y = "len", add = "none")
p
add_summary(p, "mean_sd")

# Background color ----
p <- ggboxplot(ToothGrowth, x = "dose", y = "len") +
    bgcolor("#BFD5E3") + border("#BFD5E3")
p

# Compare ----
#   Many tests can be used
df <- ToothGrowth
compare_means(len ~ 1, df, mu = 0)  # one-sample test
compare_means(len ~ supp, df)       # two-samples unpaired test
compare_means(len ~ supp, df, paired = TRUE)    # two-samples paired test
compare_means(len ~ supp, df, group.by = "dose")    # compare supp levels after grouping by dose


res <- desc_statby(ToothGrowth, measure.var = "len", grps = c("dose", "supp"))
head(res[, 1:10])

# add stat ----
p <- ggviolin(ToothGrowth, x = "dose", y = "len", add = "none")
p %>% ggadd(c("mean_sd", "jitter"), color = "dose") # add mean+/- sd and jittter
p %>% ggadd(c("boxplot", "jitter"), color = "dose") # add box plot

# ggarrange() ----
df <- ToothGrowth
df$dose <- as.factor(df$dose)

bxp <- ggboxplot(df, x = "dose", y = "len",
                 color = "dose", palette = "jco")   # boxplot
dp <- ggdotplot(df, x = "dose", y = "len", 
                color = "dose", palette = "jco")    # dotplot
dens <- ggdensity(df, x = "len", fill = "dose",
                  palette = "jco")                  # density
ggarrange(bxp, dp, dens, ncol = 2, nrow = 2)

# ggbar ----
df <- data.frame(dose = c("D0.5", "D1", "D2"),
                 len = c(4.2, 10, 29.5))
print(df)

# basic barplot with label outside
ggbarplot(df, x = "dose", y = "len",
          label = TRUE, lab.pos = "out")

# change width
ggbarplot(df, x = "dose", y = "len", width = 0.5)

# change the plot orientation: horizontal
ggbarplot(df, "dose", "len", orientation = "horiz")

# change the default order of items
ggbarplot(df, "dose", "len", order = c("D2", "D1", "D0.5"))

# change color
ggbarplot(df, "dose", "len", 
          fill = "steelblue", color = "steelblue",
          label = TRUE, lab.pos = "in", lab.col = "white")

# change color by groups (dose) with custom colors
ggbarplot(df, "dose", "len", color = "dose",
          palette = c("#00AFBB", "#E7B800", "#FC4E07"))
ggbarplot(df, "dose", "len", color = "dose", fill = "dose",
          palette = c("#00AFBB", "#E7B800", "#FC4E07"))

# plot with multiple groups --
df2 <- data.frame(supp = rep(c("VC", "OJ"), each = 3),
                  dose = rep(c("D0.5", "D1", "D2"), 2),
                  len = c(6.8, 15, 33, 4.2, 10, 29.5))
print(df2)

ggbarplot(df2, "dose", "len",
          fill = "supp", color = "supp", palette = "Paried",
          label = TRUE, lab.col = "white", lab.pos = "in")

ggbarplot(df2, "dose", "len",
          fill = "supp", color = "supp", palette = "Paired",
          label = TRUE, position = position_dodge(0.9))

# Add points and errors --
df3 <- ToothGrowth
ggbarplot(df3, x = "dose", y = "len")

ggbarplot(df3, x = "dose",  y = "len", add = "mean_se")

df4 <- group_by(df3, dose) %>% summarize(len = mean(len))
ggplot(df4) +
    geom_bar(aes(x = dose, y = len), stat = "identity")
ggplot(df4) +
    geom_col(aes(x = dose, y = len))

ggbarplot(df3, x = "dose",  y = "len", add = "mean_se",
          label = TRUE, lab.vjust = -1.6)

ggbarplot(df3, x = "dose", y = "len",
          add = "mean_se", error.plot = "upper_errorbar")

ggbarplot(df3, x = "dose", y = "len",
          add = "mean_se", error.plot = "pointrange")

ggbarplot(df3, x = "dose", y = "len",
          add = c("mean_se", "jitter"))

ggbarplot(df3, x = "dose", y = "len",
          add = c("mean_se", "dotplot"))

ggbarplot(df3, x = "dose", y = "len", color = "supp",
          add = "mean_se", palette = c("#00AFBB", "#E7B800"),
          position = position_dodge())


#########
set.seed(1234)
df <- data.frame(sex = factor(rep(c("F", "M"), each = 200)),
                 weight = c(rnorm(200, 55), rnorm(200, 58)))

ggdensity(df, x = "weight", add = "mean", rug = T, color = "sex", fill = "sex")

df.m <- df %>% group_by(sex) %>% summarise(m = mean(weight))
ggplot(df, aes(x = weight)) +
  geom_density(aes(color = sex, fill = sex), alpha = 0.3) +
  geom_vline(data = df.m, aes(xintercept = m, color = sex), linetype = "dashed")

#1. ggadd
p <- ggviolin(ToothGrowth, x = "dose", y = "len", add = "none")
p

p %>% ggadd(c("mean_sd", "jitter"), color = "dose")

p %>% ggadd(c("boxplot", "jitter"), color = "dose")

# Multiplots in one page
df <- ToothGrowth
df$dose <- as.factor(df$dose)

bxp <- ggboxplot(df, x = "dose", y = "len", color = "dose", palette = "jco")
dp <- ggdotplot(df, x = "dose", y = "len", color = "dose", palette = "jco")
dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco")

ggarrange(bxp, dp,dens, ncol = 2, nrow = 2)

ggarrange(bxp, dp,dens, common.legend = TRUE)


# Define color palette
my_cols <- c("#0D0887FF", "#6A00A8FF", "#B12A90FF",
             "#E16462FF", "#FCA636FF", "#F0F921FF")

# Standard contingency table
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Read a contingency table: housetasks
# Repartition of 13 housetasks in the couple
data <- read.delim(
  system.file("demo-data/housetasks.txt", package = "ggpubr"),
  row.names = 1
)
data

# Basic ballon plot
ggballoonplot(data)

ggballoonplot(data, fill = "value", shape = 23)+
  gradient_fill(c("blue", "white", "red"))


ggballoonplot(data, fill = "value", color = "lightgray",
              size = 10, show.label = TRUE)+
  gradient_fill(c("blue", "white", "red"))

data("Titanic")
dframe <- as.data.frame(Titanic)
head(dframe)
ggballoonplot(
  dframe, x = "Class", y = "Sex",
  size = "Freq", fill = "Freq",
  facet.by = c("Survived", "Age"),
  ggtheme = theme_bw()
)+
  scale_fill_gradientn(colors = my_cols)

df <- data.frame(dose=c("D0.5", "D1", "D2"),
                 len=c(4.2, 10, 29.5))
ggbarplot(df, x = "dose", y = "len",
          label = TRUE, label.pos = "out")
ggbarplot(df, x = "dose", y = "len", width = 0.5)

ggbarplot(df, "dose", "len",
          fill = "steelblue", color = "steelblue",
          label = TRUE, lab.pos = "in", lab.col = "white")

ggbarplot(df, "dose", "len", color = "dose",
          palette = c("#00AFBB", "#E7B800", "#FC4E07"))


data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)
df$name <- rownames(df)

ggdotchart(df, x = "name", y ="mpg",
           ggtheme = theme_bw())


df<- ToothGrowth

# Plot mean_se
ggerrorplot(df, x = "dose", y = "len")

# Change desc_stat to mean_sd
# (other values include: mean_sd, mean_ci, median_iqr, ....)
# Add labels
ggerrorplot(df, x = "dose", y = "len",
            desc_stat = "mean_sd")

# Change error.plot to "errorbar" and add mean point
# Visualize the mean of each group
ggerrorplot(df, x = "dose", y = "len",
            add = "mean", error.plot = "errorbar")

# Horizontal plot
ggerrorplot(df, x = "dose", y = "len",
            add = "mean", error.plot = "errorbar",
            orientation = "horizontal")

# Change error.plot to "crossbar"
ggerrorplot(df, x = "dose", y = "len",
            error.plot = "crossbar", width = 0.5)

# Add jitter points and errors (mean_se)
ggerrorplot(df, x = "dose", y = "len",
            add = "jitter")


df <- data.frame(dose=c("D0.5", "D1", "D2"),
                 len=c(4.2, 10, 29.5))
print(df)

# Basic plot
# +++++++++++++++++++++++++++
ggline(df, x = "dose", y = "len")

# Plot with multiple groups
# +++++++++++++++++++++

# Create some data
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                  dose=rep(c("D0.5", "D1", "D2"),2),
                  len=c(6.8, 15, 33, 4.2, 10, 29.5))
print(df2)

# Plot "len" by "dose" and
# Change line types and point shapes by a second groups: "supp"
ggline(df2, "dose", "len",
       linetype = "supp", shape = "supp")


data(diff_express)

# Default plot
ggmaplot(diff_express, main = expression("Group 1" %->% "Group 2"),
         fdr = 0.05, fc = 2, size = 0.4,
         palette = c("#B31B21", "#1465AC", "darkgray"),
         genenames = as.vector(diff_express$name),
         legend = "top", top = 20,
         font.label = c("bold", 11),
         font.legend = "bold",
         font.main = "bold",
         ggtheme = ggplot2::theme_minimal())

before <-c(200.1, 190.9, 192.7, 213, 241.4, 196.9, 172.2, 185.5, 205.2, 193.7)
after <-c(392.9, 393.2, 345.1, 393, 434, 427.9, 422, 383.9, 392.3, 352.2)

d <- data.frame(before = before, after = after)
ggpaired(d, cond1 = "before", cond2 = "after",
         fill = "condition", palette = "jco")

ggpaired(ToothGrowth, x = "supp", y = "len",
         color = "supp", line.color = "gray", line.size = 0.4,
         palette = "npg")


# Density plot
density.p <- ggdensity(iris, x = "Sepal.Length",
                       fill = "Species", palette = "jco")

# Text plot
text <- paste("iris data set gives the measurements in cm",
              "of the variables sepal length and width",
              "and petal length and width, respectively,",
              "for 50 flowers from each of 3 species of iris.",
              "The species are Iris setosa, versicolor, and virginica.", sep = " ")
text.p <- ggparagraph(text, face = "italic", size = 12)

# Arrange the plots on the same page
ggarrange(density.p, text.p,
          ncol = 1, nrow = 2,
          heights = c(1, 0.3))



df <- data.frame(
  group = c("Male", "Female", "Child"),
  value = c(25, 25, 50))

head(df)

# Basic pie charts
# ++++++++++++++++++++++++++++++++

ggpie(df, "value", label = "group")

# Change color
# ++++++++++++++++++++++++++++++++

# Change fill color by group
# set line color to white
# Use custom color palette
ggpie(df, "value", label = "group",
      fill = "group", color = "white",
      palette = c("#00AFBB", "#E7B800", "#FC4E07") )

# Change label
# ++++++++++++++++++++++++++++++++

# Show group names and value as labels
labs <- paste0(df$group, " (", df$value, "%)")
ggpie(df, "value", label = labs,
      fill = "group", color = "white",
      palette = c("#00AFBB", "#E7B800", "#FC4E07"))

# Change the position and font color of labels
ggpie(df, "value", label = labs,
      lab.pos = "in", lab.font = "white",
      fill = "group", color = "white",
      palette = c("#00AFBB", "#E7B800", "#FC4E07"))


ggscatterhist(iris, x = "Sepal.Length", y = "Sepal.Width",
              color = "#00AFBB",
              margin.params = list(fill = "lightgray"))

ggscatterhist(
  iris, x = "Sepal.Length", y = "Sepal.Width",
  color = "Species", size = 3, alpha = 0.6,
  palette = c("#00AFBB", "#E7B800", "#FC4E07"),
  margin.params = list(fill = "Species", color = "black", size = 0.2)
)

# Use boxplot as marginal
ggscatterhist(
  iris, x = "Sepal.Length", y = "Sepal.Width",
  color = "Species", size = 3, alpha = 0.6,
  palette = c("#00AFBB", "#E7B800", "#FC4E07"),
  margin.plot = "boxplot",
  ggtheme = theme_bw()
)


data("ToothGrowth")
df <- ToothGrowth

# Basic plot with summary statistics: mean_se
# +++++++++++++++++++++++++++
# Change point shapes by groups: "dose"
ggstripchart(df, x = "dose", y = "len",
             shape = "dose", size = 3,
             add = "mean_se")

# Use mean_sd
# Change error.plot to "crossbar"
ggstripchart(df, x = "dose", y = "len",
             shape = "dose", size = 3,
             add = "mean_sd", add.params = list(width = 0.5),
             error.plot = "crossbar")

# Add summary statistics
# ++++++++++++++++++++++++++

# Add box plot
ggstripchart(df, x = "dose", y = "len",
             shape = "dose", add = "boxplot")

# Add violin + mean_sd
ggstripchart(df, x = "dose", y = "len",
             shape = "dose", add = c("violin", "mean_sd"))

# Change colors
# +++++++++++++++++++++++++++
# Change colors by groups: dose
# Use custom color palette
ggstripchart(df, "dose", "len", shape = "dose",
             color = "dose", palette = c("#00AFBB", "#E7B800", "#FC4E07"),
             add = "mean_sd")


data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)
df$name <- rownames(df)
head(df[, c("wt", "mpg", "cyl")], 3)

# Textual annotation
# +++++++++++++++++
ggtext(df, x = "wt", y = "mpg",
       color = "cyl", palette = c("#00AFBB", "#E7B800", "#FC4E07"),
       label = "name", repel = TRUE)

# Add rectangle around label
ggtext(df, x = "wt", y = "mpg",
       color = "cyl", palette = c("#00AFBB", "#E7B800", "#FC4E07"),
       label = "name", repel = TRUE, label.rectangle = TRUE)


# data
df <- head(iris)

# Default table
# Remove row names using rows = NULL
ggtexttable(df, rows = NULL)

# Blank theme
ggtexttable(df, rows = NULL, theme = ttheme("blank"))


df <- mtcars
p <- ggscatter(df, x = "wt", y = "mpg",
               color = "mpg")
# Use one custom color
p + gradient_color("red")

# Two colors
p + gradient_color(c("blue", "red"))

# Three colors
p + gradient_color(c("blue", "white", "red"))

# Use RColorBrewer palette
p + gradient_color("RdYlBu")

# Use ggsci color palette
p + gradient_color("npg")


data("ToothGrowth")

# Basic plot
p <- ggboxplot(ToothGrowth, x = "dose", y = "len")
p

# Add border
p + grids(linetype = "dashed")


data("ToothGrowth")
df <- ToothGrowth

# Basic plot
p <- ggboxplot(df, x = "dose", y = "len",
               color = "dose", palette = "jco")
p
# Create horizontal plots
p + rotate()


# Load data
data("ToothGrowth")
df <- ToothGrowth

# Basic plot
p <- ggboxplot(df, x = "dose", y = "len")
p
# Vertical x axis text
p + rotate_x_text()
# Set rotation angle to 45
p + rotate_x_text(45)
p + rotate_y_text(45)


# Basic plot
p <- ggboxplot(ToothGrowth, x = "dose", y = "len",
               ggtheme = theme_gray())
p

# Remove all grids
p + rremove("grid")

# Remove only x grids
p + rremove("x.grid")


# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

# scatter plot with convex hull
ggscatter(df, x = "wt", y = "mpg", color = "cyl")+
  stat_chull(aes(color = cyl))

ggscatter(df, x = "wt", y = "mpg", color = "cyl")+
  stat_chull(aes(color = cyl, fill = cyl), alpha = 0.1, geom = "polygon")


# Load data
data("ToothGrowth")
head(ToothGrowth)

# Two independent groups
#:::::::::::::::::::::::::::::::::::::::::::::::::
p <- ggboxplot(ToothGrowth, x = "supp", y = "len",
               color = "supp", palette = "npg", add = "jitter")

# Add p-value
p + stat_compare_means()
# Change method
p + stat_compare_means(method = "t.test")

# Paired samples
#:::::::::::::::::::::::::::::::::::::::::::::::::
ggpaired(ToothGrowth, x = "supp", y = "len",
         color = "supp", line.color = "gray", line.size = 0.4,
         palette = "npg")+
  stat_compare_means(paired = TRUE)

# More than two groups
#:::::::::::::::::::::::::::::::::::::::::::::::::
# Pairwise comparisons: Specify the comparisons you want
my_comparisons <- list( c("0.5", "1"), c("1", "2"), c("0.5", "2") )
ggboxplot(ToothGrowth, x = "dose", y = "len",
          color = "dose", palette = "npg")+
  # Add pairwise comparisons p-value
  stat_compare_means(comparisons = my_comparisons, label.y = c(29, 35, 40))+
  stat_compare_means(label.y = 45) # Add global Anova p-value

# Multiple pairwise test against a reference group
ggboxplot(ToothGrowth, x = "dose", y = "len",
          color = "dose", palette = "npg")+
  stat_compare_means(method = "anova", label.y = 40)+ # Add global p-value
  stat_compare_means(aes(label = ..p.signif..),
                     method = "t.test", ref.group = "0.5")

# Multiple grouping variables
#:::::::::::::::::::::::::::::::::::::::::::::::::
# Box plot facetted by "dose"
p <- ggboxplot(ToothGrowth, x = "supp", y = "len",
               color = "supp", palette = "npg",
               add = "jitter",
               facet.by = "dose", short.panel.labs = FALSE)
# Use only p.format as label. Remove method name.
p + stat_compare_means(
  aes(label = paste0("p = ", ..p.format..))
)


# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

# scatter plot with confidence ellipses
ggscatter(df, x = "wt", y = "mpg", color = "cyl")+
  stat_conf_ellipse(aes(color = cyl))

ggscatter(df, x = "wt", y = "mpg", color = "cyl")+
  stat_conf_ellipse(aes(color = cyl, fill = cyl), alpha = 0.1, geom = "polygon")



# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

# Scatter plot with correlation coefficient
#:::::::::::::::::::::::::::::::::::::::::::::::::
sp <- ggscatter(df, x = "wt", y = "mpg",
                add = "reg.line", # Add regressin line
                add.params = list(color = "blue", fill = "lightgray"), # Customize reg. line
                conf.int = TRUE # Add confidence interval
)
# Add correlation coefficient
sp + stat_cor(method = "pearson", label.x = 3, label.y = 30)


# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

# Scatter plot with ellipses and group mean points
ggscatter(df, x = "wt", y = "mpg",
          color = "cyl", shape = "cyl", ellipse = TRUE)+
  stat_mean(aes(color = cyl, shape = cyl), size = 4)

# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

# Scatter plot with ellipses and group mean points
ggscatter(df, x = "wt", y = "mpg",
          color = "cyl", shape = "cyl",
          mean.point = TRUE, ellipse = TRUE)+
  stat_stars(aes(color = cyl))

text <- paste("iris data set gives the measurements in cm",
              "of the variables sepal length and width",
              "and petal length and width, respectively,",
              "for 50 flowers from each of 3 species of iris.",
              "The species are Iris setosa, versicolor, and virginica.", sep = "\n")

# Create a text grob
tgrob <- text_grob(text, face = "italic", color = "steelblue")
# Draw the text
as_ggplot(tgrob)


p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(aes(color = gear))

# Default plot
p

# Use theme_pubr()
p + theme_pubr()

# Format labels
p + labs_pubr()

# Basic violin plot
p <- ggviolin(ToothGrowth, x = "dose", y = "len", add = "none")
p

# Add median_iqr
add_summary(p, "mean_sd")


data("ToothGrowth")
df <- ToothGrowth
df$dose <- as.factor(df$dose)

# Create some plots
# ::::::::::::::::::::::::::::::::::::::::::::::::::
# Box plot
bxp <- ggboxplot(df, x = "dose", y = "len",
                 color = "dose", palette = "jco")
# Dot plot
dp <- ggdotplot(df, x = "dose", y = "len",
                color = "dose", palette = "jco")
# Density plot
dens <- ggdensity(df, x = "len", fill = "dose", palette = "jco")

# Arrange and annotate
# ::::::::::::::::::::::::::::::::::::::::::::::::::
figure <- ggarrange(bxp, dp, dens, ncol = 2, nrow = 2)
annotate_figure(figure,
                top = text_grob("Visualizing Tooth Growth", color = "red", face = "bold", size = 14),
                bottom = text_grob("Data source: \n ToothGrowth data set", color = "blue",
                                   hjust = 1, x = 1, face = "italic", size = 10),
                left = text_grob("Figure arranged using ggpubr", color = "green", rot = 90),
                right = "I'm done, thanks :-)!",
                fig.lab = "Figure 1", fig.lab.face = "bold"
)


# Creat some plots
bxp <- ggboxplot(iris, x = "Species", y = "Sepal.Length")
vp <- ggviolin(iris, x = "Species", y = "Sepal.Length",
               add = "mean_sd")

# Arrange the plots in one page
# Returns a gtable (grob) object
library(gridExtra)
gt <- arrangeGrob(bxp, vp, ncol = 2)

# Transform to a ggplot and print
as_ggplot(gt)


data(cars)
p <- ggscatter(cars, x = "speed", y = "dist")
p

# Set log scale
p + yscale("log2", .format = TRUE)


# Load data
data("ToothGrowth")
df <- ToothGrowth

# Basic plot
p <- ggboxplot(df, x = "dose", y = "len")
p

# Add border
p + border()


# Load data
#:::::::::::::::::::::::::::::::::::::::
data("ToothGrowth")
df <- ToothGrowth

# One-sample test
#:::::::::::::::::::::::::::::::::::::::::
compare_means(len ~ 1, df, mu = 0)

# Two-samples unpaired test
#:::::::::::::::::::::::::::::::::::::::::
compare_means(len ~ supp, df)


# Load data
data("ToothGrowth")

# Descriptive statistics
res <- desc_statby(ToothGrowth, measure.var = "len",
                   grps = c("dose", "supp"))
head(res[, 1:10])


# Default plot
ggmaplot(diff_express, main = expression("Group 1" %->% "Group 2"),
         fdr = 0.05, fc = 2, size = 0.4,
         palette = c("#B31B21", "#1465AC", "darkgray"),
         genenames = as.vector(diff_express$name),
         legend = "top", top = 20,
         font.label = c("bold", 11),
         font.legend = "bold",
         font.main = "bold",
         ggtheme = ggplot2::theme_minimal())
# Add rectangle around labesl
ggmaplot(diff_express, main = expression("Group 1" %->% "Group 2"),
         fdr = 0.05, fc = 2, size = 0.4,
         palette = c("#B31B21", "#1465AC", "darkgray"),
         genenames = as.vector(diff_express$name),
         legend = "top", top = 20,
         font.label = c("bold", 11), label.rectangle = TRUE,
         font.legend = "bold",
         font.main = "bold",
         ggtheme = ggplot2::theme_minimal())


p <- ggboxplot(ToothGrowth, x = "dose", y = "len",
               color = "supp")
print(p)
facet(p, facet.by = "supp")

# Customize
facet(p + theme_bw(), facet.by = "supp",
      short.panel.labs = FALSE, # Allow long labels in panels
      panel.labs.background = list(fill = "steelblue", color = "steelblue")
)


# Load data
data("ToothGrowth")

# Basic plot
p <- ggboxplot(ToothGrowth, x = "dose", y = "len", color = "dose",
               title = "Box Plot created with ggpubr",
               subtitle = "Length by dose",
               caption = "Source: ggpubr",
               xlab ="Dose (mg)", ylab = "Teeth length")
p

# Change the appearance of titles and labels
p +
  font("title", size = 14, color = "red", face = "bold.italic")+
  font("subtitle", size = 10, color = "orange")+
  font("caption", size = 10, color = "orange")+
  font("xlab", size = 12, color = "blue")+
  font("ylab", size = 12, color = "#993333")+
  font("xy.text", size = 12, color = "gray", face = "bold")

# Change the appearance of legend title and texts
p +
  font("legend.title", color = "blue", face = "bold")+
  font("legend.text", color = "red")


data(gene_citation)

# Some key genes of interest to be highlighted
key.gns <- c("MYC", "PRDM1", "CD69", "IRF4", "CASP3", "BCL2L1", "MYB", "BACH2", "BIM1", "PTEN",
             "KRAS", "FOXP1", "IGF1R", "KLF4", "CDK6", "CCND2", "IGF1", "TNFAIP3", "SMAD3", "SMAD7",
             "BMPR2", "RB1", "IGF2R", "ARNT")
# Density distribution
ggdensity(gene_citation, x = "citation_index", y = "..count..",
          xlab = "Number of citation",
          ylab = "Number of genes",
          fill = "lightgray", color = "black",
          label = "gene", label.select = key.gns, repel = TRUE,
          font.label = list(color= "citation_index"),
          xticks.by = 20, # Break x ticks by 20
          gradient.cols = c("blue", "red"),
          legend = "bottom",
          legend.title = "" # Hide legend title
)


# Create a scatter plot
p <- ggscatter(iris, x = "Sepal.Length", y = "Sepal.Width",
               color = "Species", palette = "jco",
               ggtheme = theme_minimal())
p

# Extract the legend. Returns a gtable
leg <- get_legend(p)

# Convert to a ggplot and print
as_ggplot(leg)
